const request = function (options) {
    const {
        url,
        method,
        data,
        onload,
        onerror,
        header
    } = options
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.open(method, url)
        xhr.setRequestHeader("Content-Type", "application/json")
        if (header) {
            for (const key in header) {
                xhr.setRequestHeader(key, header[key])
            }
        }
        xhr.onload = (e) => {
            onload && onload(e)
            resolve(JSON.parse(xhr.response))
        }
        xhr.onerror = (e) => {
            onerror && onerror(e)
            reject()
        }
        data ? xhr.send(data) : xhr.send()
    })
}

export async function getAllFiles() {
    const options = {
        url: "http://localhost:8088/getAllFiles",
        method: "GET"
    }
    const res = await request(options)
    return res.data || []
}

export async function getFile(id) {
    const options = {
        url: `http://localhost:8088/getFile/${id}`,
        method: "GET"
    }
    const res = await request(options)
    return res.data
}

export async function updateFile(id, file) {
    const options = {
        url: `http://localhost:8088/updateFile/${id}`,
        method: "PUT",
        data: JSON.stringify(file)
    }
    const res = await request(options)
    return res.code === 1 ? true : false
}

export async function createFile(file) {
    const options = {
        url: `http://localhost:8088/createFile`,
        method: "POST",
        data: JSON.stringify(file),
    }
    const res = await request(options)
    return res.code === 1 ? true : false
}

export async function deleteFile(id) {
    const options = {
        url: `http://localhost:8088/deleteFile/${id}`,
        method: "DELETE"
    }
    const res = await request(options)
    return res.code === 1 ? true : false
}

export async function getFAT() {
    const options = {
        url: `http://localhost:8088/getFAT`,
        method: "GET"
    }
    const res = await request(options)
    return res.data
}

export async function getFileByParent(parent) {
    const options = {
        url: `http://localhost:8088/getFileByParent`,
        method: "POST",
        data: parent
    }
    console.log(options)
    const res = await request(options)
    return res.data
}